<template>
  <div>
    <h1>发送兑换码</h1>
    <hr />
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      label-width="200px"
      class="demo-ruleForm"
    >
      <el-form-item label="对应用户邮箱" prop="email">
        <el-input v-model="ruleForm.email"></el-input>
        <el-button class="jianche" type="primary" size="small" @click="testing"
          >检测</el-button
        >
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')"
          >发送</el-button
        >
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      ruleForm: {
        email: "",
        customerId: "",
      },
      rules: {
        email: [{ required: true, message: "请输入邮箱", trigger: "blur" }],
      },
    };
  },
  methods: {
    testing() {
      this.$http({
        url: "/customer/selectByEmailAndCoupon",
        method: "POST",
        params: {
          email: this.ruleForm.email,
        },
      })
        .then((res) => {
          console.log("请求成功：", res.data);
          if (res.data.code == 1) {
            this.customerId = res.data.data.customerId;
            this.$message({
              message: "邮箱验证成功！",
              type: "success",
            });
          } else {
            this.customerId = null;
            this.$message.error("邮箱不存在!");
          }
        })
        .catch((err) => {
          console.log("请求失败：", err);
        });
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.customerId == null) {
            this.$message({
              type: "warning",
              message: "邮箱检测未通过!",
            });
          } else {
            this.$http({
              url: "/receiveexchangecode/insertreceive",
              method: "POST",
              data: {
                customerId: this.customerId,
                exchangeId: this.$route.query.id,
              },
            })
              .then((res) => {
                console.log("请求成功：", res);
                this.$router.push("/cpscore/convertcode");
                this.$message({
                  message: "兑换码发送成功！",
                  type: "success",
                });
              })
              .catch((err) => {
                console.log("请求失败：", err);
              });
          }
        } else {
          this.$message({
            type: "warning",
            message: "请输入邮箱!",
          });
          return false;
        }
      });
    },
    cancel() {
      this.$router.push("/cpscore/convertcode");
    },
  },
};
</script>

<style lang="scss" scoped>
.el-input {
  width: 300px;
}

.textarea {
  width: 300px;
}

hr {
  margin: 20px 0;
}

.el-form-item {
  margin: 50px 0;
}

.jianche {
  margin-left: 20px;
}
</style>